# 目标文件
TARGET = main

# 编译器
CC = /opt/arm-none-eabi/bin/arm-none-eabi-gcc
AS = /opt/arm-none-eabi/bin/arm-none-eabi-as
LD = /opt/arm-none-eabi/bin/arm-none-eabi-ld
OBJCOPY = /opt/arm-none-eabi/bin/arm-none-eabi-objcopy
SIZE = /opt/arm-none-eabi/bin/arm-none-eabi-size

# 宏定义
DEFINES = -DUSE_STDPERIPH_DRIVER -DSTM32F10X_MD -Wall -g

# 包含路径
INCLUDES = -I./library \
           -I./start \
           -I./user

# 源文件路径
SOURCES = $(wildcard ./library/*.c) \
          $(wildcard ./start/*.c) \
          $(wildcard ./user/*.c)

# 目标文件路径
OBJECTS = $(patsubst %.c,%.o,$(SOURCES))

# 编译器选项
CFLAGS = -mcpu=cortex-m3 -mthumb -O2 -Wall -fdata-sections -ffunction-sections $(DEFINES) $(INCLUDES)
ASFLAGS = -mcpu=cortex-m3 -mthumb
LDFLAGS = -m armelf -T ./start/stm32_flash.ld -e Reset_Handler -L/opt/arm-none-eabi/arm-none-eabi/lib -L/opt/arm-none-eabi/lib/gcc/arm-none-eabi/14.2.1 -lc -lgcc

# 默认目标
all: $(TARGET).hex

# 编译规则
%.o: %.c
	$(CC) $(CFLAGS) -c $< -o $@

%.o: %.s
	$(AS) $(ASFLAGS) -c $< -o $@

# 链接目标文件
$(TARGET).elf: $(OBJECTS)
	$(LD) $(LDFLAGS) -o $@ $(OBJECTS)

# 生成 .hex 文件
$(TARGET).hex: $(TARGET).elf
	$(OBJCOPY) -O ihex $< $@

# 清理生成的文件
clean:
	rm -f $(OBJECTS) $(TARGET).elf $(TARGET).hex

# 查看生成文件大小
size:
	$(SIZE) $(TARGET).elf
